<?php

declare(strict_types=1);

namespace app\admin\controller;

use think\facade\View; //模板引擎
use app\BaseController;
use think\facade\Request;
use think\exception\ValidateException;
use app\model\Admin;
use app\validate\LoginVal;
use think\facade\Session;
use app\validate\FilesVal;
use think\facade\Filesystem;
use app\model\BaseMod;
use think\facade\Cache;
use app\validate\PersonalVal;

/**
 * @name 登录系统
 */
class Login extends BaseController
{

    /**
     * @name 登录
     */
    public function login()
    {
        if (request()->isPost()) {
            $param = Request::param();
            try { //进入验证
                validate(LoginVal::class)->check($param);
            } catch (ValidateException $e) {
                return getBack(1, $e->getError());
            }
            $param['password'] = $this->md5_salt($param['password']);
            $res = Admin::log($param);
            if ($res) {
                Session::set('admin_id', $res['id']);
                $param['last_ip'] = request()->ip();
                $param['last_login'] = time();
                $param['id'] = $res['id'];
                Admin::edit($param);
                Admin::diary(['aid' => $res['id'], 'admin_user' => $res['username'], 'role' => $res['name'], 'log_time' => time(), 'log_ip' => request()->ip(), 'remark' => '登录系统']);
                return getBack(0);
            } else {
                Admin::diary(['admin_user' => $param['username'], 'role' => '未知人员', 'log_time' => time(), 'log_ip' => request()->ip(), 'remark' => '登录失败']);
                return getBack(3, '账号或密码错误!');
            }
            // return getBack(3, '', $param['password']);
        }
        return View::fetch();
    }

    /**
     * @name 退出登录
     */
    public function logout()
    {
        Session::clear();
        if (Session::get('admin_id') == "" || Session::get('admin_id') < '1') {
            return getBack(0);
        }
    }

    /**
     * @name 个人信息
     */
    public function personal()
    {
        $per = Cache::store('redis')->get('personal');
        if ($per) {
            View::assign('data', $per);
        } else {
            $id = Session::get('admin_id');
            $find = Admin::find($id);
            if ($find) {
                unset($find['password']);
                Cache::store('redis')->set('personal', $find);
                View::assign('data', $find);
            }
        }
        if (request()->isPost()) {
            $param = Request::param();
            if (mb_strlen($param['username']) < 6 || mb_strlen($param['username']) > 12) {
                return getBack(1, ['name' => 'username', 'msg' => '用户名必须6~12个字符']);
            }
            $param['id'] = Session::get('admin_id');
            $res = Admin::edit($param);
            if ($res) {
                Cache::store('redis')->clear("personal");
                return getBack(0);
            } else {
                return getBack(2);
            }
        }
        return View::fetch();
    }

    /**
     * @name 修改密码
     */
    public function uppwd()
    {
        if (request()->isPost()) {
            $param = Request::param();
            try { //进入验证
                validate(PersonalVal::class)->check($param);
            } catch (ValidateException $e) {
                return getBack(1, $e->getError());
            }
            if ($param['password'] != $param['password2']) {
                return getBack(1, ['name' => 'password2', 'msg' => '两次密码不一致']);
            }
            $data = ['id' => Session::get('admin_id'), 'password' => $this->md5_salt($param['password'])];
            $res = Admin::edit($data);
            if ($res) {
                Session::clear();
                return getBack(0);
            } else {
                return getBack(2);
            }
        }
        return View::fetch();
    }

    /**
     * @name 文件上传
     */
    public function uploads()
    {
        $filelist = read_all(root_path() . '/public/static/files');
        view::assign('filelist', $filelist);
        if (request()->isGet()) {
            $num = Request::param('num');
            $id = Request::param('id');
            View::assign('num', $num);
            View::assign('id', $id);
        }
        if (request()->isPost()) {
            $files = request()->file('file');
            $name = rand(0, 999);
            $uploads = []; //数组
            try { //进入验证
                validate(FilesVal::class)->check(['img' => $files]);
                if (is_array($files)) {
                    foreach ($files as $f) { //循环上传
                        $uploads[] = Filesystem::disk('public')->putFileAs('files', $f,  $name . "-" . $f->getOriginalName()); //上传文件并加密
                    }
                    return getBack(0, '', ['src' => $uploads[0], 'type' => $files[0]->getOriginalExtension()]);
                } else {
                    $uploads = Filesystem::disk('public')->putFileAs('files', $files,  $name . "-" . $files->getOriginalName()); //上传文件并加密
                    return getBack(0, '', ['src' => '/static//' . $uploads]);
                }
            } catch (ValidateException $e) {
                return getBack(2, $e->getError());
            }
        }
        return View::fetch();
    }

    /**
     * @name 文件删除
     */
    public function filedel()
    {
        if (request()->isPost()) {
            $path = dirname(dirname(dirname(dirname(__FILE__)))) . '/public' . Request::param('path');
            if (file_exists($path)) {
                unlink($path);
                if (file_exists($path)) {
                    return getBack(2);
                } else {
                    return getBack(0);
                }
            } else {
                return getBack(4, '文件不存在!');
            }
        }
    }

    /**
     * @name 快捷操作
     */
    public function shortcuts()
    {
        if (request()->isAjax()) {
            $param = Request::param();
            $res = BaseMod::shortcuts($param);
            if ($res) {
                return getBack(0);
            } else {
                return getBack(2);
            }
        }
    }
}
